﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PingYou.Console.Model
{
    public class DivideClassAndStudent
    {
        #region public dynamic DivideClassSaveV2(TMSDivideClassParam paramTMSDivideClass) 随机分班
        /// <summary>
        /// 随机分班
        /// </summary>
        /// <param name="paramTMSDivideClass"></param>
        /// <returns></returns>
        [HttpPost]
        public dynamic DivideClassSaveV2(TMSDivideClassParam paramTMSDivideClass)
        {
            int ClassNumber = paramTMSDivideClass.ClassNumber;//分班数量
            double StudentNumber = paramTMSDivideClass.StudentNumber;//每班人数
            //double MaleRatio = paramTMSDivideClass.MaleRatio;//男生比例
            //double FemaleRatio = paramTMSDivideClass.FemaleRatio;//女生比例
            DbCon myDbCon = new DbCon();
            try
            {
                myDbCon.Open();
                DataTable dtPreStu = TMSDivideClassPreStuManager.Search(myDbCon, new TMSDivideClassPreStuQuery
                {
                    IsPaging = false,
                    UnitID = paramTMSDivideClass.UnitID,
                    DCPlanID = paramTMSDivideClass.DCPlanID,
                }).Tables[0];

                //新增字段，小区地址
                dtPreStu.Columns.Add("New" + TMSStudentBase.HomeAddress, typeof(string));
                //1已经分配过，直接跳过，0没有分配过
                dtPreStu.Columns.Add("IsAlreadyDivided", typeof(int));
                //获取目标地址
                this.GetNewAddrsDt(dtPreStu);

                //根据性别划分、成绩升序排序
                dtPreStu.DefaultView.RowFilter = "Gender='1'";//男
                dtPreStu.DefaultView.Sort = "TotalScore ASC";
                DataTable manDt = dtPreStu.DefaultView.ToTable();

                dtPreStu.DefaultView.RowFilter = "Gender='2'";//女
                dtPreStu.DefaultView.Sort = "TotalScore ASC";
                DataTable womanDt = dtPreStu.DefaultView.ToTable();

                double totalNum = dtPreStu.Rows.Count;//学生总人数
                double totalNumM = manDt.Rows.Count;//学生男总人数
                double totalNumW = womanDt.Rows.Count;//学生女总人数
                //每班平均男女人数

                //求每个班级男女比例对应人数
                int manCount = Convert.ToInt32(StudentNumber * 1.0 / totalNum * totalNumM);
                int womanCount = Convert.ToInt32(StudentNumber * 1.0 / totalNum * totalNumW);

                //int manCount = (int)(Convert.ToInt32(totalNumM) * 1.0 / ClassNumber);
                //int womanCount = (int)(Convert.ToInt32(totalNumW) * 1.0 / ClassNumber);

                // 获取每班人数及每ID(从多到少存储)
                Dictionary<int, SplitClass> myDic = new Dictionary<int, SplitClass>();
                for (int i = 0; i < ClassNumber; i++)
                {
                    SplitClass myClass = new SplitClass();
                    myClass.ID = "";
                    myClass.ClassName = (i + 1).ToString() + "班";
                    myClass.ClassIndex = i + 1;
                    myClass.AveNum = (int)StudentNumber;
                    myClass.ManNum = manCount;
                    myClass.WomanNum = womanCount;
                    myClass.CurStudentNum = 0;
                    myClass.TotalScore = 0;
                    myClass.StudentPreList = new List<StudentPreModel>();
                    myDic[i] = myClass;
                }

                DataRow[] myDrs = null;

                //每个班级学生人数
                int lastIndexNum = 0;

                #region 1. 先分配同姓名学生
                //查询学生姓名相同的数据
                var paramStuDuShows = dtPreStu.AsEnumerable().GroupBy(p => p[TMSStudentBase.StudentName].ToString())
                    .OrderByDescending(p => p.Count())
                    .ThenBy(p => p.Key).Where(p => p.Count() > 1).Select(p => new
                    {
                        Num = p.Count(),
                        StudentName = p.Key
                    });
                //查询学生
                foreach (var stu in paramStuDuShows)
                {
                    myDrs = dtPreStu.Select(string.Format("{0}='{1}'", TMSDivideClassPreStu.StudentName, stu.StudentName));
                    //对重复学生进行循环操作，循环保存到每个班级
                    foreach (DataRow myDr in myDrs)
                    {
                        var whereCurDic = myDic.AsEnumerable().OrderBy(p => p.Value.ClassIndex).Where(p => p.Value.CurStudentNum == lastIndexNum);
                        if (whereCurDic.Count() > 0)
                        {
                            var curDic = whereCurDic.First();
                            //总学生人数
                            curDic.Value.CurStudentNum++;
                            //总成绩
                            curDic.Value.TotalScore += Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString());
                            //对应性别人数
                            if (myDr[TMSDivideClassPreStu.Gender].ToString() == "1")
                            {
                                curDic.Value.curManNum++;
                            }
                            else if (myDr[TMSDivideClassPreStu.Gender].ToString() == "2")
                            {
                                curDic.Value.curWomanNum++;
                            }
                            //新增学生
                            curDic.Value.StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = myDr[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = myDr[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = myDr["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = myDr[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = myDr[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 1,
                                ID = myDr[TMSDivideClassPreStu.ID].ToString()
                            });
                        }
                        else
                        {
                            lastIndexNum++;
                            //总学生人数
                            myDic[0].CurStudentNum++;
                            //总成绩
                            myDic[0].TotalScore += Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString());
                            //对应性别人数
                            if (myDr[TMSDivideClassPreStu.Gender].ToString() == "1")
                            {
                                myDic[0].curManNum++;
                            }
                            else if (myDr[TMSDivideClassPreStu.Gender].ToString() == "2")
                            {
                                myDic[0].curWomanNum++;
                            }
                            //新增学生
                            myDic[0].StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = myDr[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = myDr[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = myDr["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = myDr[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = myDr[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 1,
                                ID = myDr[TMSDivideClassPreStu.ID].ToString()
                            });
                        }
                    }
                }
                #endregion

                #region 2. 第二分配小区相同学生，对居住地址进行处理
                DataTable paramShortAddrStuDt = dtPreStu;
                var paramLocationDepart = paramShortAddrStuDt.AsEnumerable().GroupBy(p => p["New" + TMSStudentBase.HomeAddress].ToString()).Where(p => p.Count() > 1).Select(p => new
                {
                    Num = p.Count(),
                    NewHomeAddress = p.Key
                });

                foreach (var addr in paramLocationDepart)
                {
                    myDrs = dtPreStu.Select(string.Format("{0}='{1}'", "New" + TMSStudentBase.HomeAddress, addr.NewHomeAddress));
                    foreach (DataRow myDr in myDrs)
                    {
                        //如果已经分配，直接跳过 
                        var existsModel = from temp in myDic.AsEnumerable()
                                          where temp.Value.StudentPreList.AsEnumerable().Where(stu => stu.IdentityNumber == myDr[TMSDivideClassPreStu.IdentityNumber].ToString()).Count() > 0
                                          select new
                                          {
                                              ClassName = temp.Value.ClassName,
                                              ClassIndex = temp.Value.ClassIndex,
                                          };
                        if (existsModel.Count() > 0)
                        {
                            continue;
                        }

                        var whereCurDic = myDic.AsEnumerable().OrderBy(p => p.Value.ClassIndex).Where(p => p.Value.CurStudentNum == lastIndexNum);
                        if (whereCurDic.Count() > 0)
                        {
                            var curDic = whereCurDic.First();
                            //总学生人数
                            curDic.Value.CurStudentNum++;
                            //总成绩
                            curDic.Value.TotalScore += Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString());
                            //对应性别人数
                            if (myDr[TMSDivideClassPreStu.Gender].ToString() == "1")
                            {
                                curDic.Value.curManNum++;
                            }
                            else if (myDr[TMSDivideClassPreStu.Gender].ToString() == "2")
                            {
                                curDic.Value.curWomanNum++;
                            }
                            //新增学生
                            curDic.Value.StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = myDr[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = myDr[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = myDr["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = myDr[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = myDr[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 0,
                                ID = myDr[TMSDivideClassPreStu.ID].ToString()
                            });
                        }
                        else
                        {
                            lastIndexNum++;
                            //总学生人数
                            myDic[0].CurStudentNum++;
                            //总成绩
                            myDic[0].TotalScore += Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString());
                            //对应性别人数
                            if (myDr[TMSDivideClassPreStu.Gender].ToString() == "1")
                            {
                                myDic[0].curManNum++;
                            }
                            else if (myDr[TMSDivideClassPreStu.Gender].ToString() == "2")
                            {
                                myDic[0].curWomanNum++;
                            }
                            //新增学生
                            myDic[0].StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = myDr[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = myDr[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = myDr["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = myDr[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = myDr[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 0,
                                ID = myDr[TMSDivideClassPreStu.ID].ToString()
                            });
                        }
                    }
                }
                #endregion

                #region 3. 排除已经分配过的学生男女生
                foreach (DataRow myDr in manDt.Rows)
                {
                    if (myDr["IsAlreadyDivided"].ToString() == "1")
                    {
                        continue;
                    }
                    var existsModel = from temp in myDic.AsEnumerable()
                                      where temp.Value.StudentPreList.AsEnumerable().Where(stu => stu.IdentityNumber == myDr[TMSDivideClassPreStu.IdentityNumber].ToString()).Count() > 0
                                      select new
                                      {
                                          ClassName = temp.Value.ClassName,
                                          ClassIndex = temp.Value.ClassIndex,
                                      };
                    if (existsModel.Count() > 0)
                    {
                        myDr["IsAlreadyDivided"] = 1;
                        //manDt.Rows.Remove(myDr);
                    }
                }

                foreach (DataRow myDr in womanDt.Rows)
                {
                    var existsModel = from temp in myDic.AsEnumerable()
                                      where temp.Value.StudentPreList.AsEnumerable().Where(stu => stu.IdentityNumber == myDr[TMSDivideClassPreStu.IdentityNumber].ToString()).Count() > 0
                                      select new
                                      {
                                          ClassName = temp.Value.ClassName,
                                          ClassIndex = temp.Value.ClassIndex,
                                      };
                    if (existsModel.Count() > 0)
                    {
                        myDr["IsAlreadyDivided"] = 1;
                        //womanDt.Rows.Remove(myDr);
                    }
                }
                #endregion

                #region 4. 按照分值和性别对学生进行分班
                DataTable savePreStuDt = null;//分班学生保存
                for (int i = 0; i < myDic.Count; i++)
                {

                    //计算男女的个数是否充足，如果不足另外性别学生补足
                    //如果男生人数不足
                    if (manDt.Rows.Count < myDic[i].ManNum)
                    {
                        //判断女生是否有人补足
                        myDic[i].ManNum = manDt.Rows.Count;
                        myDic[i].WomanNum = myDic[i].AveNum - myDic[i].ManNum;
                    }
                    //如果女生不足
                    else if (womanDt.Rows.Count < myDic[i].WomanNum)
                    {
                        //男生补足
                        myDic[i].WomanNum = womanDt.Rows.Count;
                        myDic[i].ManNum = myDic[i].AveNum - myDic[i].WomanNum;
                    }

                    for (int s = 1; s <= 2; s++)
                    {
                        savePreStuDt = s == 1 ? womanDt : manDt;
                        SaveClassTempStudent(myDbCon, myDic[i], s, savePreStuDt, true);
                    }
                }
                #endregion

                #region 5.1 调整班级学生成绩数据  --- 总分差距小于100

                Random myRandom = new Random();

                //获取差距最大的两个班级--对这两个班级进行调整
                //curMaxIndex = this.GetMaxDic(myDic);
                //curMinIndex = this.GetMinDic(myDic);
                //double leftScore = myDic[curMaxIndex].TotalScore - myDic[curMinIndex].TotalScore;
                int curGender = -1;
                //while (leftScore < 100)
                //{
                //    curGender = myRandom.Next(1, 3);
                //    //班级分值进行变动
                //    var paramMaxFirstStu = myDic[curMaxIndex].StudentPreList.AsEnumerable().Where(p => p.IsNotAlowChange == 0 && p.Gender == curGender.ToString()).OrderByDescending(p => p.Score).First();

                //    //首先查询对应性别的响应分数的学生，如果没有，则默认查询差距最大的同性别学生
                //    var paramMinFirsrStu = myDic[curMinIndex].StudentPreList.AsEnumerable().Where(p => p.IsNotAlowChange == 0 && p.Gender == paramMaxFirstStu.Gender).OrderBy(p => p.Score).First();

                //    myDic[curMinIndex].StudentPreList.Remove(paramMinFirsrStu);
                //    myDic[curMinIndex].StudentPreList.Add(paramMaxFirstStu);

                //    myDic[curMaxIndex].StudentPreList.Remove(paramMaxFirstStu);
                //    myDic[curMaxIndex].StudentPreList.Add(paramMinFirsrStu);

                //    curMaxIndex = this.GetMaxDic(myDic);
                //    curMinIndex = this.GetMinDic(myDic);
                //    leftScore = myDic[curMaxIndex].TotalScore - myDic[curMinIndex].TotalScore;
                //}
                #endregion

                #region 5.2 调整班级学生成绩数据  --- 平均分差距小于10
                //获取差距最大的两个班级--对这两个班级进行调整

                int curMaxIndex = this.GetMaxAVGDic(myDic);
                int curMinIndex = this.GetMinAVGDic(myDic);
                double leftScoreAvg = (myDic[curMaxIndex].TotalScore * 1.0 / myDic[curMaxIndex].CurStudentNum) - (myDic[curMinIndex].TotalScore * 1.0 / myDic[curMinIndex].CurStudentNum);
                int loopMax = 100;
                int curLoop = 0;
                while (leftScoreAvg > 2.0 && curLoop < loopMax)
                {
                    curGender = myRandom.Next(1, 3);
                    //班级分值进行变动
                    var paramMaxFirstStu = myDic[curMaxIndex].StudentPreList.AsEnumerable().Where(p => p.IsNotAlowChange == 0 && p.Gender == curGender.ToString()).OrderByDescending(p => p.Score).First();

                    //首先查询对应性别的响应分数的学生，如果没有，则默认查询差距最大的同性别学生
                    var paramMinFirsrStu = myDic[curMinIndex].StudentPreList.AsEnumerable().Where(p => p.IsNotAlowChange == 0 && p.Gender == paramMaxFirstStu.Gender).OrderBy(p => p.Score).First();

                    myDic[curMinIndex].StudentPreList.Remove(paramMinFirsrStu);
                    myDic[curMinIndex].StudentPreList.Add(paramMaxFirstStu);

                    myDic[curMaxIndex].StudentPreList.Remove(paramMaxFirstStu);
                    myDic[curMaxIndex].StudentPreList.Add(paramMinFirsrStu);

                    curMaxIndex = this.GetMaxAVGDic(myDic);
                    curMinIndex = this.GetMinAVGDic(myDic);
                    leftScoreAvg = (myDic[curMaxIndex].TotalScore * 1.0 / myDic[curMaxIndex].CurStudentNum) - (myDic[curMinIndex].TotalScore * 1.0 / myDic[curMinIndex].CurStudentNum);
                    curLoop++;
                }
                #endregion

                #region 5. 保存分班情况
                //先创建班级
                string paramClassCode = string.Empty;
                string DivideClassID = string.Empty;
                for (int i = 0; i < myDic.Count; i++)
                {
                    paramClassCode = string.Empty;
                    myDic[i].ID = SaveClass(myDbCon, paramTMSDivideClass, myDic[i].ClassName, paramTMSDivideClass.GradeCode, out paramClassCode);//保存分班班级
                    myDic[i].ClassCode = paramClassCode;
                }
                #endregion

                #region 5.保存Demo表信息
                this.SaveDemoClassAndStudent(myDbCon, myDic, paramTMSDivideClass);
                #endregion

                #region 6. 保存学生情况
                this.SaveClassStudentV2(myDbCon, myDic, paramTMSDivideClass);
                #endregion

                #region 7. 更新分班状态
                //更新分班计划状态
                //TMSDivideClassPlanManager.Update(myDbCon, TMSDivideClassPlan.State, "1", paramTMSDivideClass.DCPlanID);
                #endregion

                return new { success = true };
            }
            catch (Exception myEx)
            {
                myEx.Out();
                return new { success = false, message = myEx.Message };
            }
            finally
            {
                myDbCon.Close();
            }
        }

        #region 按照总分随机分班
        [HttpPost]
        public dynamic DivideClassSaveOrderByTotal(TMSDivideClassParam paramTMSDivideClass)
        {
            int ClassNumber = paramTMSDivideClass.ClassNumber;//分班数量
            double StudentNumber = paramTMSDivideClass.StudentNumber;//每班人数
            double MaleRatio = paramTMSDivideClass.MaleRatio;//男生比例
            double FemaleRatio = paramTMSDivideClass.FemaleRatio;//女生比例
            DbCon myDbCon = new DbCon();
            try
            {
                myDbCon.Open();
                DataTable dtPreStu = TMSDivideClassPreStuManager.Search(myDbCon, new TMSDivideClassPreStuQuery
                {
                    IsPaging = false,
                    UnitID = paramTMSDivideClass.UnitID,
                    DCPlanID = paramTMSDivideClass.DCPlanID,
                }).Tables[0];
                //根据性别划分、成绩升序排序
                dtPreStu.DefaultView.RowFilter = "Gender='1'";//男
                dtPreStu.DefaultView.Sort = "TotalScore ASC";
                DataTable manDt = dtPreStu.DefaultView.ToTable();
                dtPreStu.DefaultView.RowFilter = "Gender='2'";//女
                dtPreStu.DefaultView.Sort = "TotalScore ASC";
                DataTable womanDt = dtPreStu.DefaultView.ToTable();

                double totalNum = dtPreStu.Rows.Count;//学生总人数
                double totalNumM = manDt.Rows.Count;//学生男总人数
                double totalNumW = womanDt.Rows.Count;//学生女总人数
                //每班平均男女人数

                int manCount = Convert.ToInt32(MaleRatio / (MaleRatio + FemaleRatio) * StudentNumber);
                int womanCount = Convert.ToInt32(FemaleRatio / (MaleRatio + FemaleRatio) * StudentNumber);
                //int manCount = Convert.ToInt32(StudentNumber * 1.0 / totalNum * totalNumM);
                //int womanCount = Convert.ToInt32(StudentNumber * 1.0 / totalNum * totalNumW);

                // 获取每班人数及每ID(从多到少存储)
                Dictionary<int, SplitClass> myDic = new Dictionary<int, SplitClass>();
                for (int i = 0; i < ClassNumber; i++)
                {
                    SplitClass myClass = new SplitClass();
                    myClass.ID = "";
                    myClass.ClassName = (i + 1).ToString() + "班";
                    myClass.AveNum = (int)StudentNumber;
                    myClass.ManNum = manCount;
                    myClass.WomanNum = womanCount;
                    myDic[i] = myClass;
                }

                string DivideClassID = string.Empty;//分班班级ID
                DataTable savePreStuDt = null;//分班学生保存
                int num = 0;//分班人数
                for (int i = 0; i < myDic.Count; i++)
                {
                    string ClassCode = string.Empty;
                    DivideClassID = SaveClass(myDbCon, paramTMSDivideClass, myDic[i].ClassName, paramTMSDivideClass.GradeCode, out ClassCode);//保存分班班级

                    //计算男女的个数是否不足，如果不足另外性别学生补足

                    //如果男生人数不足
                    if (manDt.Rows.Count < myDic[i].ManNum)
                    {
                        //判断女生是否有人补足
                        myDic[i].ManNum = manDt.Rows.Count;
                        myDic[i].WomanNum = myDic[i].AveNum - myDic[i].ManNum;
                    }
                    else if (womanDt.Rows.Count < myDic[i].WomanNum)
                    {
                        //男生补足
                        myDic[i].WomanNum = womanDt.Rows.Count;
                        myDic[i].ManNum = myDic[i].AveNum - myDic[i].WomanNum;
                    }

                    for (int s = 1; s <= 2; s++)
                    {
                        num = s == 1 ? myDic[i].WomanNum : myDic[i].ManNum;
                        savePreStuDt = s == 1 ? womanDt : manDt;
                        ScoreRuleStudent(myDbCon, paramTMSDivideClass.UnitID, paramTMSDivideClass.DCPlanID, DivideClassID, ClassCode, num, savePreStuDt, false);
                    }
                }
                //更新分班计划状态
                TMSDivideClassPlanManager.Update(myDbCon, TMSDivideClassPlan.State, "1", paramTMSDivideClass.DCPlanID);
                return new { success = true };
            }
            catch (Exception myEx)
            {
                myEx.Out();
                return new { success = false, message = myEx.Message };
            }
            finally
            {
                myDbCon.Close();
            }
        }
        #endregion

        #region public dynamic SaveClass(TMSDivideClassData paramTMSDivideClass) 分班保存班级数据
        /// <summary>
        /// 分班保存班级数据
        /// </summary>
        /// <param name="myDbCon"></param>
        /// <param name="paramTMSDivideClass"></param>
        /// <param name="paramClassNumber">班级名数字</param>
        /// <returns></returns>
        public string SaveClass(DbCon myDbCon, TMSDivideClassParam paramTMSDivideClass, string paramClassName, string gradeCode, out string ClassCode)
        {
            UserInfo userinfo = CommonMethod.GetUserInfo();
            string paramID = string.Empty;
            try
            {
                Dictionary<String, object> myParam = new Dictionary<String, object>();
                myParam.Add(TMSDivideClass.UnitID, paramTMSDivideClass.UnitID);
                myParam.Add(TMSDivideClass.DCPlanID, paramTMSDivideClass.DCPlanID);
                myParam.Add(TMSDivideClass.ClassName, paramClassName);
                bool result = TMSDivideClassManager.Exists(myDbCon, myParam);//判断班级是否存在
                if (!result)
                {
                    Dictionary<String, object> whereParam = new Dictionary<String, object>();
                    whereParam.Add(TMSDivideClass.UnitID, paramTMSDivideClass.UnitID);
                    whereParam.Add(TMSDivideClass.DCPlanID, paramTMSDivideClass.DCPlanID);
                    int index = TMSDivideClassManager.QueryDT(myDbCon, whereParam, 1).Rows.Count;
                    ClassCode = gradeCode + (index + 1).ToString().PadLeft(2, '0');

                    TMSDivideClassManager myTMSDivideClass = new TMSDivideClassManager();
                    myTMSDivideClass.UnitID = paramTMSDivideClass.UnitID;
                    myTMSDivideClass.AnnualSemesterID = paramTMSDivideClass.AnnualSemesterID;
                    myTMSDivideClass.DCPlanID = paramTMSDivideClass.DCPlanID;
                    myTMSDivideClass.GradeBaseID = paramTMSDivideClass.GradeBaseID;
                    myTMSDivideClass.GradeName = paramTMSDivideClass.GradeName;
                    myTMSDivideClass.ClassCode = ClassCode;
                    myTMSDivideClass.ClassName = paramClassName;
                    myTMSDivideClass.Remark = paramTMSDivideClass.Remark;
                    myTMSDivideClass.CreateStaff = userinfo.UserID;
                    paramID = myTMSDivideClass.Insert(myDbCon);
                }
                else
                {
                    TMSDivideClassManager myTMSDivideClass = new TMSDivideClassManager();
                    myTMSDivideClass.Get(myDbCon, myParam);
                    paramID = myTMSDivideClass.ID.ToString();
                    ClassCode = myTMSDivideClass.ClassCode.ToString();
                }
            }
            catch (Exception myEx)
            {
                myEx.Out();
                ClassCode = string.Empty;
            }
            return paramID;
        }
        #endregion

        #region private bool ScoreRuleStudent()保存分班规则学生
        /// <summary>
        /// 保存分班规则学生
        /// </summary>
        /// <param name="myDbCon">myDbCon</param>
        /// <param name="UnitID">单位</param>
        /// <param name="DCPlanID">分班计划</param>
        /// <param name="DivideClassID">分班ID</param>
        /// <param name="num">分班学生数量</param>
        /// <param name="saveDt">分班学生数据集</param>
        /// <returns></returns>
        private bool ScoreRuleStudent(DbCon myDbCon, string UnitID, string DCPlanID, string DivideClassID, string ClassCode, int num, DataTable saveDt, bool IsAvgScore)
        {
            try
            {

                if (IsAvgScore)
                {
                    //获取平均分值
                    double cnum = num / 2.0;//成绩平均，高分数和低分数各获取一半,低分数要多
                    int snum = cnum.ToString().IndexOf(".") == -1 ? Convert.ToInt32(cnum) : (int)cnum + 1;
                    int dnum = num - snum;
                    // 高分数人员保存
                    for (int x = 0; x < dnum; x++)
                    {
                        if (saveDt.Rows.Count > 0)
                        {
                            SaveClassStudent(myDbCon, UnitID, DCPlanID, DivideClassID, saveDt.Rows[saveDt.Rows.Count - 1]["ID"].ToString(), ClassCode);
                            saveDt.Rows.RemoveAt(saveDt.Rows.Count - 1);
                        }
                    }
                    // 低分数人员保存
                    for (int x = 0; x < snum; x++)
                    {
                        if (saveDt.Rows.Count > 0)
                        {
                            SaveClassStudent(myDbCon, UnitID, DCPlanID, DivideClassID, saveDt.Rows[0]["ID"].ToString(), ClassCode);
                            saveDt.Rows.RemoveAt(0);
                        }
                    }
                }
                else
                {
                    //求最大值或者最小值
                    for (int x = 0; x < num; x++)
                    {
                        if (saveDt.Rows.Count > 0)
                        {
                            SaveClassStudent(myDbCon, UnitID, DCPlanID, DivideClassID, saveDt.Rows[saveDt.Rows.Count - 1]["ID"].ToString(), ClassCode);
                            saveDt.Rows.RemoveAt(saveDt.Rows.Count - 1);
                        }
                    }
                }
                return true;
            }
            catch (Exception myEx)
            {
                throw myEx;
            }
        }
        #endregion

        #region 保存分班规则学生，按照总分从上到下抽取学生
        #endregion

        #region public bool SaveClassStudent()保存分班学生
        /// <summary>
        /// 保存分班学生
        /// </summary>
        /// <param name="myDbCon">myDbCon</param>
        /// <param name="UnitID">单位</param>
        /// <param name="DCPlanID">分班计划</param>
        /// <param name="DivideClassID">分班ID</param>
        /// <param name="studentID">学生ID</param>
        /// <returns></returns>
        public bool SaveClassStudent(DbCon myDbCon, string UnitID, string DCPlanID, string DivideClassID, string studentID, string classCode)
        {
            try
            {
                Dictionary<String, object> myParam = new Dictionary<String, object>();
                myParam.Add(TMSDivideClassStu.UnitID, UnitID);
                myParam.Add(TMSDivideClassStu.DCPlanID, DCPlanID);
                myParam.Add(TMSDivideClassStu.PreStudentID, studentID);
                bool result = TMSDivideClassStuManager.Exists(myDbCon, myParam);//判断班级是否存在
                if (!result)
                {
                    Dictionary<String, object> whereParam = new Dictionary<String, object>();
                    whereParam.Add(TMSDivideClassStu.UnitID, UnitID);
                    whereParam.Add(TMSDivideClassStu.DCPlanID, DCPlanID);
                    whereParam.Add(TMSDivideClassStu.DivideClassID, DivideClassID);
                    int index = TMSDivideClassStuManager.QueryDT(myDbCon, whereParam, 1).Rows.Count;
                    TMSDivideClassStuManager myClassStudent = new TMSDivideClassStuManager();
                    myClassStudent.UnitID = UnitID;
                    myClassStudent.DCPlanID = DCPlanID;
                    myClassStudent.DivideClassID = DivideClassID;
                    myClassStudent.ClassStuCode = DateTime.Now.ToString("yyyyMMdd") + classCode + (index + 1).ToString().PadLeft(3, '0');
                    myClassStudent.PreStudentID = studentID;
                    myClassStudent.Save(myDbCon);
                }
                return true;
            }
            catch (Exception myEx)
            {
                CommonMethod.WriteLogErr(myEx.Message);
                throw myEx;
            }
        }

        public bool SaveClassStudentV2(DbCon myDbCon, Dictionary<int, SplitClass> myDic, TMSDivideClassParam myTMSDivideClass)
        {
            UserInfo userInfo = CommonMethod.GetUserInfo();
            string paramNowDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string UnitID = string.Empty, DCPlanID = string.Empty, DivideClassID = string.Empty, studentID = string.Empty, classCode = string.Empty;
            try
            {
                Dictionary<String, object> whereParam = new Dictionary<String, object>();
                whereParam.Add(TMSDivideClassStu.UnitID, UnitID);
                whereParam.Add(TMSDivideClassStu.DCPlanID, DCPlanID);
                DataTable myClassStudentDt = TMSDivideClassStuManager.QueryDT(myDbCon, whereParam, 1);
                TMSDivideClassStuManager myClassStudent = new TMSDivideClassStuManager();
                DataTable myNewClassStudentDt = myClassStudent.NewInstance();

                DataRow myNewDr = null;
                DataRow[] myDrs = null;
                foreach (SplitClass myClass in myDic.Values)
                {
                    //bool result = TMSDivideClassStuManager.Exists(myDbCon, myParam);//判断班级是否存在
                    //if (!result)
                    //{
                    foreach (StudentPreModel myStudent in myClass.StudentPreList)
                    {
                        //如果学生已经存在分班记录，则直接跳过
                        myDrs = myClassStudentDt.Select(string.Format("{0}='{1}'", TMSDivideClassStu.StudentBaseID, myStudent.StudentBaseID));
                        if (myDrs.Length > 0)
                        {
                            continue;
                        }
                        //如果存在预分班学生已经分班的情况， 直接跳过
                        myDrs = myClassStudentDt.Select(string.Format("{0}='{1}'", TMSDivideClassStu.ID, myStudent.ID));
                        if (myDrs.Length > 0)
                        {
                            continue;
                        }

                        myNewDr = myNewClassStudentDt.NewRow();
                        myNewDr[TMSDivideClassStu.ID] = CommonMethod.GuidNewGuid();
                        myNewDr[TMSDivideClassStu.UnitID] = myTMSDivideClass.UnitID;
                        myNewDr[TMSDivideClassStu.DCPlanID] = myTMSDivideClass.DCPlanID;
                        myNewDr[TMSDivideClassStu.DivideClassID] = myClass.ID;
                        myNewDr[TMSDivideClassStu.PreStudentID] = myStudent.ID;
                        myNewDr[TMSDivideClassStu.ClassStuCode] = "";
                        myNewDr[TMSDivideClassStu.StudentBaseID] = myStudent.StudentBaseID;
                        myNewDr[TMSDivideClassStu.Enabled] = "1";
                        myNewDr[TMSDivideClassStu.CreateStaff] = userInfo.UserID;
                        myNewDr[TMSDivideClassStu.CreateDate] = paramNowDateTime;
                        myNewDr[TMSDivideClassStu.ModifyStaff] = userInfo.UserID;
                        myNewDr[TMSDivideClassStu.ModifyDate] = paramNowDateTime;
                        myNewClassStudentDt.Rows.Add(myNewDr);
                    }

                }
                if (myNewClassStudentDt.Rows.Count > 0)
                {
                    TMSDivideClassStuManager.InsertTable(myNewClassStudentDt);
                }
                return true;
            }
            catch (Exception myEx)
            {
                myEx.Out();
                throw myEx;
            }
        }

        public bool SaveDemoClassAndStudent(DbCon myDbCon, Dictionary<int, SplitClass> myDic, TMSDivideClassParam myTMSDivideClass)
        {
            UserInfo userInfo = CommonMethod.GetUserInfo();
            string paramNowDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            try
            {
                DemoSplitClassManager myDemoSplitClassManager = new DemoSplitClassManager();
                DemoSplitClassStuManager myDemoSplitClassStuManager = new DemoSplitClassStuManager();
                DataTable myNewClassDt = myDemoSplitClassManager.NewInstance();

                DataTable myNewClassStudentDt = myDemoSplitClassStuManager.NewInstance();
                DataRow myNewDr = null;
                string paramClassID = string.Empty;
                foreach (SplitClass myClass in myDic.Values)
                {
                    myNewDr = myNewClassDt.NewRow();
                    paramClassID = CommonMethod.GuidNewGuid();
                    myNewDr[DemoSplitClass.ID] = paramClassID;
                    myNewDr[DemoSplitClass.UnitID] = myTMSDivideClass.UnitID;
                    myNewDr[DemoSplitClass.Remark] = "";
                    myNewDr[DemoSplitClass.Enabled] = "1";
                    myNewDr[DemoSplitClass.ClassName] = myClass.ClassName;
                    myNewDr[DemoSplitClass.AveNum] = myClass.AveNum;
                    myNewDr[DemoSplitClass.ManNum] = myClass.ManNum;
                    myNewDr[DemoSplitClass.WomanNum] = myClass.WomanNum;
                    myNewDr[DemoSplitClass.curManNum] = myClass.curManNum;
                    myNewDr[DemoSplitClass.curWomanNum] = myClass.curWomanNum;
                    myNewDr[DemoSplitClass.TotalScore] = myClass.TotalScore;
                    myNewDr[DemoSplitClass.CurStudentNum] = myClass.CurStudentNum;
                    myNewDr[DemoSplitClass.ClassCode] = myClass.ClassCode;
                    myNewDr[DemoSplitClass.ClassIndex] = myClass.ClassIndex;
                    myNewDr[DemoSplitClass.CreateStaff] = userInfo.UserID;
                    myNewDr[DemoSplitClass.CreateDate] = paramNowDateTime;
                    myNewDr[DemoSplitClass.ModifyStaff] = userInfo.UserID;
                    myNewDr[DemoSplitClass.ModifyDate] = paramNowDateTime;
                    myNewClassDt.Rows.Add(myNewDr);
                    foreach (StudentPreModel myStudent in myClass.StudentPreList)
                    {
                        myNewDr = myNewClassStudentDt.NewRow();
                        myNewDr[DemoSplitClassStu.ID] = CommonMethod.GuidNewGuid();
                        myNewDr[DemoSplitClassStu.SplitClassID] = paramClassID;
                        myNewDr[DemoSplitClassStu.UnitID] = myTMSDivideClass.UnitID;
                        myNewDr[DemoSplitClassStu.Remark] = "";
                        myNewDr[DemoSplitClassStu.Enabled] = "1";
                        myNewDr[DemoSplitClassStu.CreateStaff] = userInfo.UserID;
                        myNewDr[DemoSplitClassStu.CreateDate] = paramNowDateTime;
                        myNewDr[DemoSplitClassStu.ModifyStaff] = userInfo.UserID;
                        myNewDr[DemoSplitClassStu.ModifyDate] = paramNowDateTime;
                        myNewDr[DemoSplitClassStu.StudentBaseID] = myStudent.StudentBaseID;
                        myNewDr[DemoSplitClassStu.StudentName] = myStudent.StudentName;
                        myNewDr[DemoSplitClassStu.IdentityNumber] = myStudent.IdentityNumber;
                        myNewDr[DemoSplitClassStu.Score] = myStudent.Score;
                        myNewDr[DemoSplitClassStu.Gender] = myStudent.Gender;
                        myNewDr[DemoSplitClassStu.Address] = myStudent.Address;
                        myNewDr[DemoSplitClassStu.ParentMaxEdu] = myStudent.ParentMaxEdu;
                        myNewDr[DemoSplitClassStu.IsNotAlowChange] = myStudent.IsNotAlowChange;
                        myNewClassStudentDt.Rows.Add(myNewDr);
                    }
                }
                if (myNewClassDt.Rows.Count > 0)
                {
                    DemoSplitClassManager.InsertTable(myNewClassDt);
                }
                if (myNewClassStudentDt.Rows.Count > 0)
                {
                    DemoSplitClassStuManager.InsertTable(myNewClassStudentDt);
                }
                return true;
            }
            catch (Exception ex)
            {
                ex.Out();
                return false;
            }
        }

        //临时保存分班学生，后面还需要根据学生姓名和居住小区进行进行部分调整
        /// <summary>
        /// 
        /// </summary>
        /// <param name="myDbCon"></param>
        /// <param name="myDic"></param>
        /// <param name="genderType">1女生类型，2男生类型</param>
        /// <param name="divideClassNum">分班人数</param>
        /// <param name="saveDt">学生数据源</param>
        /// <param name="IsAvgScore"></param>
        /// <returns></returns>
        public bool SaveClassTempStudent(DbCon myDbCon, SplitClass myClass, int genderType, DataTable saveDt, bool IsAvgScore)
        {
            int paramDivideClassNum = -1;
            int curGenderNum = -1;
            try
            {
                if (genderType == 1)
                {
                    //女生可容纳个数
                    paramDivideClassNum = myClass.WomanNum - myClass.curWomanNum;
                    curGenderNum = myClass.curWomanNum;

                }
                else if (genderType == 2)
                {
                    //男生可容纳个数
                    paramDivideClassNum = myClass.ManNum - myClass.curManNum;
                    curGenderNum = myClass.curManNum;
                }

                if (IsAvgScore)
                {
                    //获取平均分值
                    double cnum = paramDivideClassNum / 2.0;//成绩平均，高分数和低分数各获取一半,低分数要多
                    int snum = cnum.ToString().IndexOf(".") == -1 ? Convert.ToInt32(cnum) : (int)cnum + 1;
                    int dnum = paramDivideClassNum - snum;

                    bool isPersonExists = true;
                    // 高分数人员保存
                    for (int x = 0; x < dnum; x++)
                    {
                        if (saveDt.Rows.Count == 0)
                        {
                            break;
                        }
                        var rowModel = saveDt.Rows[saveDt.Rows.Count - 1];
                        while (rowModel["IsAlreadyDivided"].ToString() == "1")
                        {
                            saveDt.Rows.RemoveAt(saveDt.Rows.Count - 1);
                            if (saveDt.Rows.Count == 0)
                            {
                                isPersonExists = false;
                                break;
                            }
                            rowModel = saveDt.Rows[saveDt.Rows.Count - 1];
                        }
                        if (!isPersonExists)
                        {
                            break;
                        }

                        if (saveDt.Rows.Count > 0)
                        {
                            //curDic.Value.TotalScore += Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString());
                            myClass.CurStudentNum++;
                            myClass.TotalScore += Convert.ToDouble(rowModel[TMSDivideClassPreStu.TotalScore].ToString());
                            curGenderNum++;
                            myClass.StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = rowModel[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = rowModel[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = rowModel["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = rowModel[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(rowModel[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = rowModel[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 0,
                                ID = rowModel[TMSDivideClassPreStu.ID].ToString()
                            });
                            saveDt.Rows.RemoveAt(saveDt.Rows.Count - 1);
                        }
                    }
                    isPersonExists = true;
                    // 低分数人员保存
                    for (int x = 0; x < snum; x++)
                    {
                        if (saveDt.Rows.Count == 0)
                        {
                            break;
                        }
                        var rowModel = saveDt.Rows[0];
                        while (rowModel["IsAlreadyDivided"].ToString() == "1")
                        {
                            saveDt.Rows.RemoveAt(0);
                            if (saveDt.Rows.Count == 0)
                            {
                                isPersonExists = false;
                                break;
                            }
                            rowModel = saveDt.Rows[0];
                        }
                        if (!isPersonExists)
                        {
                            break;
                        }

                        //var rowModel = saveDt.Rows[0];
                        if (saveDt.Rows.Count > 0)
                        {
                            //curDic.Value.TotalScore += Convert.ToDouble(myDr[TMSDivideClassPreStu.TotalScore].ToString());
                            myClass.CurStudentNum++;
                            myClass.TotalScore += Convert.ToDouble(rowModel[TMSDivideClassPreStu.TotalScore].ToString());
                            curGenderNum++;
                            myClass.StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = rowModel[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = rowModel[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = rowModel["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = rowModel[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(rowModel[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = rowModel[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 0,
                                ID = rowModel[TMSDivideClassPreStu.ID].ToString()
                            });
                            saveDt.Rows.RemoveAt(0);
                        }
                    }
                }
                else
                {
                    //求最大值或者最小值
                    for (int x = 0; x < paramDivideClassNum; x++)
                    {
                        var rowModel = saveDt.Rows[saveDt.Rows.Count - 1];
                        if (saveDt.Rows.Count > 0)
                        {
                            myClass.CurStudentNum++;
                            myClass.TotalScore += Convert.ToDouble(rowModel[TMSDivideClassPreStu.TotalScore].ToString());
                            curGenderNum++;
                            myClass.StudentPreList.Add(new StudentPreModel()
                            {
                                StudentName = rowModel[TMSDivideClassPreStu.StudentName].ToString(),
                                StudentBaseID = rowModel[TMSDivideClassPreStu.StudentBaseID].ToString(),
                                Address = rowModel["New" + TMSStudentBase.HomeAddress].ToString(),
                                Gender = rowModel[TMSDivideClassPreStu.Gender].ToString(),
                                Score = Convert.ToDouble(rowModel[TMSDivideClassPreStu.TotalScore].ToString()),
                                IdentityNumber = rowModel[TMSDivideClassPreStu.IdentityNumber].ToString(),
                                IsNotAlowChange = 0,
                                ID = rowModel[TMSDivideClassPreStu.ID].ToString()
                            });
                            saveDt.Rows.RemoveAt(saveDt.Rows.Count - 1);
                        }
                    }
                }

                if (genderType == 1)
                {
                    myClass.curWomanNum = curGenderNum;
                }
                else if (genderType == 2)
                {
                    myClass.curManNum = curGenderNum;
                }

                return true;
            }
            catch (Exception myEx)
            {
                throw myEx;
            }
        }
        #endregion
        #endregion

    }
}
